package com.example.widgetappone;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import java.security.PrivateKey;
import java.util.Observable;
import java.util.Observer;

import static com.example.widgetappone.Constants.DEBUG_TAG;

public class WidgetService extends Service implements Observer {
    private static final String TAG = "WidgetService";
    public static final String START_ACTION = "action.start.loop";
    public static final String STOP_ACTION = "action.stop.loop";
    private Handler handler = new Handler();
    private boolean shouldStop;
    private Runnable runnable;
    private AppWidgetProvider appWidgetProvider = AppWidgetProvider.getInstance();
    private int i;
    private String loopText;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(DEBUG_TAG, "WidgetService onCreate: ");
        WidgetObservable.getInstance().addObserver(this);
        runnable = () -> {
            loopText = "循环" + i;
            updateWidget();
            i = i + 1;
        };

        startLoop();

        startNotificationForeground();

    }

    private void startNotificationForeground() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String CHANNEL_ID = "NFCService";
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel Channel = new NotificationChannel(CHANNEL_ID, "主服务", NotificationManager.IMPORTANCE_HIGH);
            Channel.enableLights(true);//设置提示灯
            Channel.setLightColor(Color.RED);//设置提示灯颜色
            Channel.setShowBadge(true);//显示logo
            Channel.setDescription("bottombar notification");//设置描述
            Channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); //设置锁屏可见 VISIBILITY_PUBLIC=可见
            if (manager != null) {
                manager.createNotificationChannel(Channel);
            }

            Notification notification = new Notification.Builder(this)
                    .setChannelId(CHANNEL_ID)
                    .setAutoCancel(false)
                    .setContentTitle("主服务")//标题
                    .setContentText("运行中...")//内容
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher)//小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                    .build();
            startForeground(1, notification);//服务前台化只能使用startForeground()方法,不能使用 notificationManager.notify(1,notification); 这个只是启动通知使用的,使用这个方法你只需要等待几秒就会发现报错了
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d(DEBUG_TAG, "onStartCommand: ");

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(DEBUG_TAG, "WidgetService onDestroy: ");
        shouldStop = true;
        handler.removeCallbacks(runnable);
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void startLoop() {
        if (!shouldStop) {
            if (!handler.hasCallbacks(runnable)) {
                handler.postDelayed(runnable, 1000);
            }
        }
    }

    /**
     * notify appwidgetprovider need to refresh widget ui
     */
    private void updateWidget() {
        Log.d(TAG, "updateWidget " + loopText);
        appWidgetProvider.notifyChange(this);
        startLoop();
    }


    @Override
    public void update(Observable o, Object arg) {
        Intent intent = (Intent) arg;
        String action = intent.getAction();
        if (START_ACTION.equals(action)) {
            Log.d(TAG, "onStart()");
            shouldStop = false;
            startLoop();
        } else if (STOP_ACTION.equals(action)) {
            Log.d(TAG, "onStop()");
            i = 0;
            shouldStop = true;
            handler.removeCallbacks(runnable);
        }
    }

    public int getI() {
        return i;
    }

    public String getLoopText() {
        return loopText;
    }
}
